package com.atguigu.util;

import com.atguigu.service.UserService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk实现代理：
 *     a.通过反射实现代理，需要实现接口方法
 */
public class ProxyUtil<T> {

    public <T>T getService(T type){
        //通过事项该内部类事项代理
        InvocationHandler invocationHandler=new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = null;//接受数据和调用方法,afterReturning
                try {
                    //before
                    before(method);
                    invoke = method.invoke(proxy, args, type);
                    //after
                    after(method);
                } catch (Exception e) {
                    //afterThrowing
                    throw handleException(e,method);
                }
                return invoke;
            }
        };
        //在通过反射调用相对应的类
        Class<?>[] interfaces = this.getClass().getInterfaces();
        ClassLoader classLoader = this.getClass().getClassLoader();
        Object proxy = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);

        return (T) proxy;
    }

    public void before(Method method){

    }

    public void after(Method method){

    }

    public Exception handleException(Exception exception,Method method){
        Throwable cause = exception.getCause();
        String message=method+":"+cause;
        return new Exception(message);
    }

}
